﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WooCoo.ObjectModel.ManagedProperty
{
    /// <summary>
    /// 托管属性值与元数据
    /// </summary>
    public interface IFieldData : ITrackStatus
    {
        /// <summary>
        /// 字段对应的属性值
        /// </summary>
        object Value { get; set; }
    }

    /// <summary>
    /// 泛型接口
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IFieldData<T> : IFieldData
    {
        new T Value { get; set; }
    }

    [Serializable]
    public class FieldData<T> : IFieldData<T>
    {
        private T _data;
        private bool _isDirty;

        public virtual T Value
        {
            get { return _data; }
            set { _data = value; _isDirty = true; }
        }

        object IFieldData.Value
        {
            get
            {
                return this.Value;
            }
            set
            {
                if (value == null)
                    this.Value = default(T);
                else
                    this.Value = (T)value;
            }
        }

        /// <summary>
        /// 获取字段是否发生改变        
        /// </summary>
        public virtual bool IsDirty
        {
            get
            {
                ITrackStatus child = _data as ITrackStatus;
                if (child != null)
                {
                    return child.IsDirty;

                }
                else
                {
                    return _isDirty;
                }
            }
        }

        bool ITrackStatus.IsValid
        {
            get { return IsValid; }
        }

        /// <summary>
        /// 判断字段是否可用，包含对聚合类判断
        /// </summary>
        protected virtual bool IsValid
        {
            get
            {
                ITrackStatus child = _data as ITrackStatus;
                if (child != null)
                {
                    return child.IsValid;
                }
                else
                {
                    return true;
                }
            }
        }

        /// <summary>
        /// 字段是否为子对象
        /// </summary>
        //bool ITrackStatus.IsChild
        //{
        //    get
        //    {
        //        ITrackStatus child = _data as ITrackStatus;
        //        if (child != null)
        //        {
        //            return child.IsChild;
        //        }
        //        else
        //        {
        //            return false;
        //        }
        //    }
        //}

        /// <summary>
        /// 将标记字段为未改变.
        /// </summary>
        public virtual void MarkClean()
        {
            _isDirty = false;
        }
    }
}
